/**
 *  Copyright 2011 Marco Berri - marcoberri@gmail.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 **/
package com.stats;

import com.utils.Default;
import com.utils.StringUtil;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.digest.DigestUtils;

/**
 *
 * @author Marco Berri marcoberri@gmail.com
 */
public class Base extends com.Base {

    /**
     * Per ora lasciamo aperto il login poi si vedrà
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private boolean logged = true;
    private boolean logout = false;
    private String username;
    private String password;
    private String proxy = "/";
    /**
     * totali visualizzazioni
     */
    protected String tot_view;
    /**
     * totali salvataggi
     */
    protected String tot_save;
    /**
     * totali ultimo aggiornamento
     */
    protected String tot_ts;

    /**
     * 
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        logged = Default.toBoolean(request.getSession().getAttribute("logged"), this.logged);

        logout = Default.toBoolean(request.getParameter("logout"), false);

        if (logout) {
            logged = false;
            request.getSession().removeAttribute("user");
        }

        if (!logged) {

            //verifico se ci sono i parametri per eseguire i login
            username = Default.toString(request.getParameter("username"), null);
            password = Default.toString(request.getParameter("password"), null);
            if (StringUtil.isNullOrEmpty(username) || StringUtil.isNullOrEmpty(password)) {

                response.sendRedirect("/stats");
                return;
            } //cripto la password
            debug("password:" + password);
            String pwd_crypt = DigestUtils.sha256Hex(password);
            HashMap user = new HashMap();
            try {
                Statement stat = this.conn_stats.createStatement();
                ResultSet rsstats = stat.executeQuery("select * from login where username='" + username + "' and password='" + pwd_crypt + "'");
                while (rsstats.next()) {
                    logged = true;
                    ResultSetMetaData rsmd = rsstats.getMetaData();
                    int numColumns = rsmd.getColumnCount();
                    // Get the column names; column indices start from 1
                    for (int i = 1; i < numColumns + 1; i++) {
                        user.put(rsmd.getColumnName(i), rsstats.getString(i));
                    }
                    debug("user: " + user);
                }
                request.getSession().setAttribute("user", user);
            } catch (SQLException ex) {
                fatal("SQLException", ex);
            }

        }

        request.getSession().setAttribute("logged", logged);

        try {
            Statement stat = this.conn_stats.createStatement();

            //statistiche totali di vista e salvataggio nel tempo e prendo l'ultima
            ResultSet rsstats = stat.executeQuery("select * from counter order by ts desc limit 1");
            while (rsstats.next()) {
                tot_view = rsstats.getString("n_save");
                tot_save = rsstats.getString("n_view");
                tot_ts = rsstats.getString("ts");
            }
        } catch (SQLException e) {
        }

    }
}
